package com.kexun.config.system;

import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.WebRequest;

import java.util.HashMap;
import java.util.Map;

@Component
public class ErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
        Object error = webRequest.getAttribute("error", RequestAttributes.SCOPE_REQUEST);
        if (error != null) {
            return (Map<String, Object>) error;
        } else {
            return getErrMap(webRequest);
        }

    }


    private Map<String, Object> getErrMap(WebRequest webRequest) {
        HashMap<String, Object> errMap = new HashMap<>();
        Integer statusCode = (Integer) webRequest.getAttribute("javax.servlet.error.status_code", RequestAttributes.SCOPE_REQUEST);
        if (statusCode == null) {
            errMap.put("code", 999);
            errMap.put("message", "未知错误");
            return errMap;
        }
        errMap.put("code", statusCode);
        try {
            errMap.put("message", HttpStatus.valueOf(statusCode).getReasonPhrase());
        } catch (Exception ex) {
            errMap.put("message", "Http Status " + statusCode);
        }
        return errMap;
    }


    @Override
    public String toString() {
        return "kexunErrorAttributes{}";
    }
}
